package cloud.gateway.mygateway;

import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @auther xfanonymous
 * @create 2023-12-31 21:41
 *
 * Gateway Filter3
 * 自定义单一过滤器，只有满足要求的请求才能通过
 * http://localhost:9527/pay/gateway/filter?status=123 才能通过
 * http://localhost:9527/pay/gateway/filter 无法通过
 *
 * 1. gateway9527新建MyGatewayFilterFactory，类名以xxxGatewayFilterFactory结尾
 * 2. 继承AbstractGatewayFilterFactory，<>内为当前类.Config
 * 3. @Component
 * 4. 无参构造函数，内部调用super
 * 5. 新建Config内部类，定义配置文件中的参数
 * 6. 重写apply()、shortcutFieldOrder()方法
 * 7. 在yml配置类中配置自定义断言，以 -xx 自定义断言类的前缀作为配置参数顶层，如 -My
 * 8. 格式：-自定义类前缀 = 指定代码内部类Config中的参数值
 */
@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.Config>
{
    public MyGatewayFilterFactory()
    {
        super(MyGatewayFilterFactory.Config.class);
    }

    // 定义配置文件中的参数，匹配状态后，才可以访问
    public static class Config
    {
        @Getter
        @Setter
        private String status;
    }

    @Override
    public GatewayFilter apply(MyGatewayFilterFactory.Config config)
    {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
            {
                ServerHttpRequest request = exchange.getRequest();

                // 获取配置文件中的参数
                System.out.println("进入了自定义网关过滤器MyGatewayFilterFactory，status："
                        +config.getStatus());

                if (request.getQueryParams().containsKey("xfanonymous")) {
                    return chain.filter(exchange);
                } else {
                    exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                    return exchange.getResponse().setComplete();
                }
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("status");
    }
}